package service;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.UserDao;
import entry.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String change = req.getParameter("change");
        String enroll = req.getParameter("enroll");
        String random = req.getParameter("random");

        User user = objectMapper.readValue(req.getInputStream(), User.class);
        HttpSession session = req.getSession(false);
        User sessionUser = null;
        if (session != null){
            sessionUser = (User)session.getAttribute("user");
        }
        UserDao userDao = new UserDao();

        // 是要随机生成头像
        if (random != null && random.equals("yes")){

            String photoName = sessionUser.getUsername();
            int photoNumber = Integer.parseInt(sessionUser.getPhoto().split("_")[1])+1;
            sessionUser.setPhoto(photoName + "_" + photoNumber);// 更新用户头像名

            // 删除原来的照片
            String path = "/root/tomcat/apache-tomcat-8.5.78/webapps/blog/image/";
            User.deletePhoto(sessionUser.getUsername(), path);
            // 生成新的照片
            path += photoName + "_" + photoNumber + ".png";
            DrawPicture.generateImg(sessionUser.getUsername(), path);

            // 更新 session的值
            session.removeAttribute("user");
            session.setAttribute("user", sessionUser);
            // 更新数据库信息
            userDao.updateUser(sessionUser.getUserId(), sessionUser);
            resp.getWriter().write("success");
            return;
        }


        if (user == null || user.getUsername() == null || user.getUsername().equals("")) {
            resp.getWriter().write("usernameNull");
            return;
        }
        if (user.getPassword() == null || user.getPassword().equals("")) {
            resp.getWriter().write("passwordNull");
            return;
        }

        // 是要登录或注册
        // 核查信息是否正确
        User checkUser = userDao.getUserByName(user.getUsername());

        // 是要修改信息
        if (change != null && sessionUser != null && change.equals("yes")){

            // 看用户是否存在
            if (checkUser != null && !checkUser.getUsername().equals(sessionUser.getUsername())){
                resp.getWriter().write("exist");
                return;
            }
            // 更新照片的名字
            String Path = "/root/tomcat/apache-tomcat-8.5.78/webapps/blog/image/";
            String oldPath = Path + sessionUser.getPhoto() + ".png";
            String newPath = Path + user.getUsername() + "_1.png";
            File oldPhoto = new File(oldPath);
            File newPhoto = new File(newPath);
            oldPhoto.renameTo(newPhoto);

            User tempUser = userDao.getUserByName(sessionUser.getUsername());
            tempUser.setUsername(user.getUsername());
            tempUser.setGithub(user.getGithub());
            tempUser.setPhoto(user.getUsername()+"_1");
            tempUser.setPassword(user.getPassword());

            // 更新用户信息
            int userId = tempUser.getUserId();
            userDao.updateUser(userId, tempUser);
            // 更新 session数据
            session.removeAttribute("user");
            tempUser.setPassword("");
            session.setAttribute("user", tempUser);
            resp.getWriter().write("success");
            return;
        }

        // 是要注册
        if (enroll != null && enroll.equals("yes")){
            // 注册用户
            // 看用户是否存在
            if (checkUser != null){
                resp.getWriter().write("exist");
                return;
            }
            // 生成头像
            user.setPhoto(user.getUsername() + "_1");
            String path = "/root/tomcat/apache-tomcat-8.5.78/webapps/blog/image/" + user.getUsername() + "_1.png";
            DrawPicture.generateImg(user.getUsername(), path);

            // 添加用户到数据库
            userDao.enroll(user);
            resp.getWriter().write("success");
            return;
        }
        if (checkUser == null || !checkUser.getPassword().equals(user.getPassword())) {
            resp.getWriter().write("failed");
        }else {
            // 登录成功
            resp.getWriter().write("success");
            session = req.getSession();
            checkUser.setPassword("");
            session.setAttribute("user", checkUser);
        }
    }
}
